import {useMutation, UseMutationOptions, UseMutationResult, useQuery, useQueryClient} from "@tanstack/react-query";
import axios, {AxiosError} from "axios";
import {User} from "./types";
import {useAccountStore} from "../store/store";


export const useLogin = (
    config: UseMutationOptions<
        { jwt?: string; message?:string}, //返回值
        AxiosError<ApiErrorResponse>,
        { username: string; password: string }
    > = {}
) => {
    const queryClient = useQueryClient();
    return useMutation(
        async ({username, password}) => {
            const resp = await axios.post('/account/login', {
                username,
                password
            }).catch((err)=>{
                return err;
            });

            if (resp.data?.jwt){
                // useAccountDetail()
                queryClient.prefetchQuery(["accountDetail"], async () => {
                    const resp = await axios.get('/account/detail').catch((err)=>{
                        return err;
                    });
                    return resp.data ? resp.data : resp;
                })

            }

            return resp.data ? resp.data : resp;
        },
        config
    );
}


export const useAccountDetail = () => {
    return useQuery(["accountDetail"], async () => {
        const resp = await axios.post('/account/detail').catch((err)=>{
            return err;
        });
        return resp.data ? resp.data : resp;
    })
}
